package cn.edu.buu.hospital.web;

import cn.edu.buu.hospital.entity.*;
import cn.edu.buu.hospital.service.*;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 前端主控制器 - 处理用户端功能
 */
@Controller
@RequestMapping("/frontend")
public class FrontendController {

    @Autowired
    private HospitalService hospitalService;
    
    @Autowired
    private DepartmentService departmentService;
    
    @Autowired
    private VisitService visitService;
    
    @Autowired
    private AppointmentService appointmentService;
    
    @Autowired
    private PayService payService;
    
    @Autowired
    private ReportService reportService;
    
    @Autowired
    private UserService userService;

    /**
     * 首页 - 显示医院列表
     */
    @GetMapping("/index")
    public String index(Model model) {
        List<Hospital> hospitals = hospitalService.findAll();
        model.addAttribute("hospitals", hospitals);
        return "frontend/index";
    }

    /**
     * 浏览科室 - 根据医院ID显示科室列表
     */
    @GetMapping("/departments")
    public String departments(@RequestParam("hospitalId") Long hospitalId, Model model) {
        List<Department> departments = departmentService.findByHospitalId(hospitalId);
        Hospital hospital = hospitalService.findById(hospitalId);
        model.addAttribute("departments", departments);
        model.addAttribute("hospital", hospital);
        return "frontend/departments";
    }

    /**
     * 查看医生排班 - 根据科室ID显示排班信息
     */
    @GetMapping("/schedules")
    public String schedules(@RequestParam("deptId") Long deptId, 
                           @RequestParam(value = "date", required = false) String date,
                           Model model) {
        List<Visit> schedules = visitService.findByDeptId(deptId);
        Department department = departmentService.findById(deptId);
        
        // 如果指定了日期，过滤排班
        if (date != null && !date.isEmpty()) {
            schedules = schedules.stream()
                .filter(schedule -> schedule.getVisitDate() != null && schedule.getVisitDate().equals(date))
                .collect(java.util.stream.Collectors.toList());
        }
        
        model.addAttribute("schedules", schedules);
        model.addAttribute("department", department);
        model.addAttribute("selectedDate", date);
        return "frontend/schedules";
    }

    /**
     * 预约挂号页面
     */
    @GetMapping("/book")
    public String bookAppointment(@RequestParam("visitId") Long visitId, 
                                 HttpSession session, Model model) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }
        
        Visit visit = visitService.findById(visitId);
        if (visit == null) {
            model.addAttribute("error", "排班信息不存在");
            return "frontend/schedules";
        }
        
        model.addAttribute("visit", visit);
        return "frontend/book";
    }

    /**
     * 提交预约
     */
    @PostMapping("/book")
    public String submitAppointment(@RequestParam("visitId") Long visitId,
                                   @RequestParam("patientName") String patientName,
                                   @RequestParam("patientPhone") String patientPhone,
                                   @RequestParam("symptoms") String symptoms,
                                   HttpSession session, Model model) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }

        try {
            // 检查排班是否还有空位
            Visit visit = visitService.findById(visitId);
            if (visit.getUsedNum() >= visit.getMaxNum()) {
                model.addAttribute("error", "该时段预约已满");
                return "frontend/book";
            }

            // 创建预约记录
            Appointment appointment = new Appointment();
            appointment.setUserid(loginUser.getUserid());
            appointment.setVisitid(visitId);
            appointment.setPatientName(patientName);
            appointment.setPatientPhone(patientPhone);
            appointment.setSymptoms(symptoms);
            appointment.setStatus(0); // 待支付
            // 设置预约创建时间，只使用LocalDateTime类型
            appointment.setCreatetime(LocalDateTime.now());
            // createTime字符串由getCreateTimeString方法自动生成，无需手动设置
            
            // 生成预约号
            String appointmentNo = "AP" + System.currentTimeMillis();
            appointment.setNumber(appointmentNo);

            appointmentService.add(appointment);
            
            // 更新排班已预约数量
            visitService.updateUsedNum(visitId);
            
            model.addAttribute("success", "预约成功，请及时支付");
            model.addAttribute("appointmentNo", appointmentNo);
            return "frontend/payment";
        } catch (Exception e) {
            model.addAttribute("error", "预约失败：" + e.getMessage());
            return "frontend/book";
        }
    }

    /**
     * 在线缴费页面
     */
    @GetMapping("/payment")
    public String payment(@RequestParam("appointmentNo") String appointmentNo, 
                         HttpSession session, Model model) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }

        // 根据预约号查找预约信息
        Appointment appointment = appointmentService.findByNumber(appointmentNo);
        if (appointment == null) {
            model.addAttribute("error", "预约信息不存在");
            return "frontend/index";
        }

        model.addAttribute("appointment", appointment);
        return "frontend/payment";
    }

    /**
     * 提交支付
     */
    @PostMapping("/payment")
    public String submitPayment(@RequestParam("appointmentId") Long appointmentId,
                               @RequestParam("amount") Double amount,
                               @RequestParam("payMethod") String payMethod,
                               HttpSession session, Model model) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }

        try {
            // 获取当前时间作为支付时间
            LocalDateTime now = LocalDateTime.now();
            String payTimeStr = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            
            // 创建支付记录
            Pay pay = new Pay();
            pay.setAppointmentId(appointmentId);
            pay.setAmount(BigDecimal.valueOf(amount));
            pay.setPayMethod(payMethod);
            pay.setPayStatus(1); // 已支付
            pay.setCreatetime(now);
            pay.setPayTime(payTimeStr);
            
            // 生成订单号
            String orderNo = "PAY" + System.currentTimeMillis();
            pay.setOrderNo(orderNo);

            payService.add(pay);
            
            // 更新预约状态为已支付
            Appointment appointment = appointmentService.findById(appointmentId);
            appointment.setStatus(1); // 已支付（根据业务逻辑，0-待支付，1-已支付，2-已完成）
            appointmentService.modify(appointment);
            
            // 设置会话属性，用于支付成功页面显示
            session.setAttribute("payTime", payTimeStr);
            
            model.addAttribute("success", "支付成功");
            model.addAttribute("orderNo", orderNo);
            
            // 检查该预约ID是否已有报告
            Report reportCondition = new Report();
            reportCondition.setAppointmentid(appointmentId);
            PageInfo<Report> existingReports = reportService.find(1, 1, reportCondition);
            
            // 如果没有报告，则自动生成一个基础病单报告
            if (existingReports == null || existingReports.getList() == null || existingReports.getList().isEmpty()) {
                // 获取预约详情信息
                Appointment appointmentDetail = appointmentService.findById(appointmentId);
                
                // 创建病单报告
                Report report = new Report();
                report.setAppointmentid(appointmentId);
                report.setUserid(loginUser.getUserid());
                
                // 简化科室信息获取逻辑，不依赖复杂的关联对象
                String departmentName = "未知科室";
                try {
                    // 尝试直接从预约对象中获取visit和department信息
                    if (appointmentDetail.getVisit() != null) {
                        // 如果有visit对象，检查是否能直接获取科室名（可能通过deptId再查询）
                        // 这里简化处理，直接设置一个默认科室名称
                        departmentName = "预约科室";
                    }
                } catch (Exception e) {
                    // 忽略关联对象访问异常
                }
                
                // 设置症状描述
                report.setSymptoms("患者已支付，等待就诊。");
                report.setDoctoradvice("待医生诊断后更新");
                report.setCreatetime(LocalDateTime.now());
                report.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                
                reportService.add(report);
            }
            
            // 重定向到支付成功页面
            return "frontend/payment-success";
        } catch (Exception e) {
            model.addAttribute("error", "支付失败：" + e.getMessage());
            return "frontend/payment";
        }
    }

    /**
     * 我的预约列表
     */
    @GetMapping("/my-appointments")
    public String myAppointments(HttpSession session, Model model) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }

        List<Appointment> appointments = appointmentService.findByUserId(loginUser.getUserid());
        model.addAttribute("appointments", appointments);
        return "frontend/my-appointments";
    }

    /*
     * 以下写病单功能已被禁用
     *//**
     * 医生写病单页面
     */
    // 以下方法已被禁用 - 添加病单报告功能已取消
    // @GetMapping("/write-report")
    // public String writeReport(@RequestParam("appointmentId") Long appointmentId, 
    //                          HttpSession session, Model model) {
    //     User loginUser = (User) session.getAttribute("loginUser");
    //     if (loginUser == null) {
    //         return "redirect:/auth/login";
    //     }
    //     // 检查用户是否为医生
    //     if (loginUser.getType() != 2) {
    //         model.addAttribute("error", "只有医生可以写病单");
    //         return "frontend/index";
    //     }
    //
    //     Appointment appointment = appointmentService.findById(appointmentId);
    //     if (appointment == null) {
    //         model.addAttribute("error", "预约信息不存在");
    //         return "frontend/index";
    //     }
    //
    //     model.addAttribute("appointment", appointment);
    //     return "frontend/write-report";
    // }
    
    // /**
    //  * 提交病单
    //  */
    // @PostMapping("/write-report")
    // public String submitReport(@RequestParam("appointmentId") Long appointmentId,
    //                           @RequestParam("symptoms") String symptoms,
    //                           @RequestParam("doctorAdvice") String doctorAdvice,
    //                           HttpSession session, Model model) {
    //     User loginUser = (User) session.getAttribute("loginUser");
    //     if (loginUser == null) {
    //         return "redirect:/auth/login";
    //     }
    //
    //     try {
    //         // 创建病单报告
    //         Report report = new Report();
    //         report.setAppointmentid(appointmentId);
    //         report.setUserid(loginUser.getUserid());
    //         report.setSymptoms(symptoms);
    //         report.setDoctoradvice(doctorAdvice);
    //         report.setCreatetime(LocalDateTime.now());
    //         report.setCreateTime(LocalDateTime.now().toString());
    //
    //         reportService.add(report);
    //         
    //         // 更新预约状态为已完成
    //         Appointment appointment = appointmentService.findById(appointmentId);
    //         appointment.setStatus(1); // 已完成（根据Appointment实体类定义，0-待就诊，1-已完成，2-已取消）
    //         appointmentService.modify(appointment);
    //         
    //         model.addAttribute("success", "病单已生成");
    //         return "frontend/report-success";
    //     } catch (Exception e) {
    //         model.addAttribute("error", "生成病单失败：" + e.getMessage());
    //         return "frontend/write-report";
    //     }
    // }
    
    /**
     * 查看个人信息
     */
    @GetMapping("/profile")
    public String profile(HttpSession session, Model model,
                         @RequestParam(value = "editMode", required = false, defaultValue = "false") boolean editMode) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }
        
        // 查询完整的用户信息
        User user = userService.findById(loginUser.getUserid());
        model.addAttribute("user", user);
        model.addAttribute("editMode", editMode);
        
        return "frontend/profile";
    }
    
    /**
     * 更新个人信息
     */
    @PostMapping("/update-profile")
    public String updateProfile(User user,
                               @RequestParam(value = "file", required = false) MultipartFile file,
                               HttpSession session, Model model) {
        try {
            User loginUser = (User) session.getAttribute("loginUser");
            if (loginUser == null) {
                return "redirect:/auth/login";
            }
            
            // 如果有上传新头像，则处理文件
            if (file != null && !file.isEmpty()) {
                ServletContext application = session.getServletContext();
                String serverRealPath = application.getRealPath("statics/images/adminHead/");
                String originalFilename = file.getOriginalFilename();
                String fileExtendsName = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + fileExtendsName;
                
                // 确保目录存在
                java.io.File dir = new java.io.File(serverRealPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                
                Path path = Paths.get(serverRealPath, fileName);
                file.transferTo(path);
                user.setHeadpic(fileName);
            }
            
            // 设置用户ID
            user.setUserid(loginUser.getUserid());
            // 执行更新操作
            userService.modify(user);
            
            // 更新session中的用户信息
            User updatedUser = userService.findById(user.getUserid());
            session.setAttribute("loginUser", updatedUser);
            
            model.addAttribute("user", updatedUser);
            model.addAttribute("success", "个人信息更新成功！");
            model.addAttribute("editMode", false);
            
            return "frontend/profile";
        } catch (Exception e) {
            model.addAttribute("error", "更新失败: " + e.getMessage());
            model.addAttribute("user", user);
            model.addAttribute("editMode", true);
            return "frontend/profile";
        }
    }
    
    /**
     * 患者首页 - 显示概览信息和快捷操作
     */
    @GetMapping("/patient-index")
    public String patientIndex(HttpSession session, Model model) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }
        
        // 获取用户最近的预约记录（最多3条）
        List<Appointment> recentAppointments = appointmentService.findByUserId(loginUser.getUserid());
        if (recentAppointments != null && recentAppointments.size() > 3) {
            recentAppointments = recentAppointments.subList(0, 3);
        }
        model.addAttribute("recentAppointments", recentAppointments);
        return "frontend/patient-index";
    }
    
    /**
     * 我的就诊记录
     */
    @GetMapping("/my-reports")
    public String myReports(HttpSession session, Model model) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/auth/login";
        }
        
        // 获取用户的所有预约记录
        List<Appointment> appointments = appointmentService.findByUserId(loginUser.getUserid());
        
        // 过滤出已完成的预约，获取对应的就诊记录
        List<Map<String, Object>> reportsList = new ArrayList<>();
        for (Appointment appointment : appointments) {
            if (appointment.getStatus() == 1) { // 已完成的预约（根据实体类定义，1表示已完成）
                // 使用条件查询方法查找报告
                Report condition = new Report();
                condition.setAppointmentid(appointment.getAppointmentid());
                PageInfo<Report> reportPage = reportService.find(1, 1, condition);
                if (reportPage != null && reportPage.getList() != null && !reportPage.getList().isEmpty()) {
                    Report report = reportPage.getList().get(0);
                    Map<String, Object> reportMap = new HashMap<>();
                    reportMap.put("appointment", appointment);
                    reportMap.put("report", report);
                    reportsList.add(reportMap);
                }
            }
        }
        
        model.addAttribute("reportsList", reportsList);
        return "frontend/my-reports";
    }
}
